﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using LeoGemini.Service.Infrastructure.Handler.Exception;
using OrderService.Domain.Shared.Enum;
using Volo.Abp.Auditing;
using Volo.Abp.Domain.Entities;

namespace OrderService.Domain.Aggregate.Order
{
    [Table("tb_order")]
    public class Order : AggregateRoot<Guid>, IHasCreationTime, IHasModificationTime
    {
        /// <summary>
        /// ORM框架使用
        /// </summary>
        protected Order()
        {
            
        }

        public Order(Guid id)
        {
            Id = id;
            Items = new List<OrderItem>();
            Distribute = new Distribute();
            State = OrderState.WaitingForPay;
        }

        public Order(Guid id, Guid referenceUserId) : this(id)
        {
            ReferenceUserId = referenceUserId;
        }
        
        /// <summary>
        /// 所属用户id
        /// </summary>
        [Column("reference_user_id")]
        public virtual Guid ReferenceUserId { get; private set; }

        /// <summary>
        /// 总价
        /// </summary>
        [Column("total_price")]
        public virtual decimal TotalPrice { get; private set; }
        
        /// <summary>
        /// 实际支付价格
        /// </summary>
        [Column("paid_price")]
        public virtual decimal PaidPrice { get; private set; }
        
        /// <summary>
        /// 支付流水号
        /// </summary>
        [Column("in_trade_no")]
        public virtual string InTradeNo { get; private set; }
        
        /// <summary>
        /// 是否支付
        /// </summary>
        [Column("is_paid")]
        public virtual bool IsPaid { get; private set; }
        
        /// <summary>
        /// 支付时间
        /// </summary>
        [Column("paid_time")]
        public virtual DateTime PaidTime { get; private set; }

        private OrderState _state;

        /// <summary>
        /// 订单状态
        /// </summary>
        [Column("state")]
        public virtual OrderState State
        {
            get => _state;
            private set
            {
                // 订单已关闭
                if (State == OrderState.Closed)
                    throw new BadRequestException(ErrorMessage.CAN_NOT_REWRITE_CLOSED);

                _state = value;
            } 
        }

        /// <summary>
        /// 配送信息
        /// </summary>
        [Column("distribute")]
        public virtual Distribute Distribute { get; private set; }
        
        /// <summary>
        /// 关闭原因
        /// </summary>
        [Column("reason")]
        public virtual string Reason { get; private set; }
        
        /// <summary>
        /// 订单条目
        /// </summary>
        public virtual ICollection<OrderItem> Items { get; private set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public virtual DateTime CreationTime { get; set; }

        /// <summary>
        /// 最后修改时间
        /// </summary>
        public DateTime? LastModificationTime { get; set; }

        /// <summary>
        /// 计算实际支付价格
        /// </summary>
        public void CalcPaidPrice()
        {
            PaidPrice = TotalPrice;
        }

        /// <summary>
        /// 订单付款
        /// </summary>
        public void HasBeenPaid(string inTradeNo)
        {
            // 订单状态不正确
            if (State != OrderState.WaitingForPay)
                throw new BadRequestException(ErrorMessage.ORDER_STATE_ERROR);
            
            // 记录支付状态及流水
            IsPaid = true;
            InTradeNo = inTradeNo;
            PaidTime = DateTime.Now;

            // 订单待配送
            State = OrderState.WaitingForDistribute;
        }
        
        /// <summary>
        /// 订单发货
        /// </summary>
        public void HasBeenDispatch(string shipNo)
        {
            // 快递单号不合法
            if (string.IsNullOrEmpty(shipNo))
                throw new BadRequestException(ErrorMessage.SHIP_NO_IS_NULL);

            // 订单状态不正确
            if (State != OrderState.WaitingForDistribute)
                throw new BadRequestException(ErrorMessage.ORDER_STATE_ERROR);
            
            // 记录发货信息
            Distribute.ShipNo = shipNo;
            Distribute.DistributedTime = DateTime.Now;
            
            // 订单待签收
            State = OrderState.WaitingForSigned;
        }

        /// <summary>
        /// 订单签收
        /// </summary>
        public void HasBeenSigned()
        {
            // 订单状态不正确
            if (State != OrderState.WaitingForSigned)
                throw new BadRequestException(ErrorMessage.ORDER_STATE_ERROR);
            
            // 记录签收信息
            Distribute.SignedTime = DateTime.Now;
            State = OrderState.WaitingForConfirm;
        }

        /// <summary>
        /// 订单确认
        /// </summary>
        public void HasBeenConfirmed()
        {
            // 订单状态不正确
            if (State != OrderState.WaitingForConfirm)
                throw new BadRequestException(ErrorMessage.ORDER_STATE_ERROR);

            // 订单已完成
            State = OrderState.Done;
        }

        /// <summary>
        /// 订单退货
        /// </summary>
        public void HasBeenRejected()
        {
            // 重复操作
            if (State == OrderState.Closed || State == OrderState.Rejected)
                throw new BadRequestException(ErrorMessage.CAN_NOT_REPEAT_ACTION);
            
            // 订单已退货
            State = OrderState.Rejected;
        }

        /// <summary>
        /// 订单关闭
        /// </summary>
        public void HasBeenClosed(string reason)
        {
            Reason = reason;
            State = OrderState.Closed;
        }
    }
}